package com.lzh.persevere.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.persevere.mapper.MenuMapper;
import com.lzh.persevere.model.entity.Menu;
import com.lzh.persevere.model.vo.menu.MenuVO;
import com.lzh.persevere.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 菜单权限表(SysMenu)表服务实现类
 *
 * @author luzhiheng
 * @since 2023-12-28
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<MenuVO> findMenuList() {
        List<MenuVO> menuVOList = BeanUtil.copyToList(baseMapper.selectList(null), MenuVO.class);
        List<MenuVO> parentList = menuVOList.stream().filter(e -> e.getParentId() == null || e.getParentId() == -1).collect(Collectors.toList());
        List<MenuVO> subList = menuVOList.stream().filter(e -> e.getParentId() != null && e.getParentId() != -1).collect(Collectors.toList());
        for (MenuVO menuVO : parentList) {
            buildTree(menuVO, subList);
        }
        return parentList;
    }

    private void buildTree(MenuVO parent, List<MenuVO> subList) {
        if (CollectionUtil.isEmpty(subList) || parent == null) {
            return;
        }
        List<MenuVO> list = subList.stream().filter(e -> Objects.equals(e.getParentId(), parent.getId())).collect(Collectors.toList());
        List<MenuVO> list1 = subList.stream().filter(e -> !Objects.equals(e.getParentId(), parent.getId())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(list)) {
            parent.setChildren(list);
        }
        for (MenuVO sub : list) {
            buildTree(sub, list1);
        }
    }
}

